#pragma once
#include <iostream>
#include <fstream>
#include <string>
#include <unordered_map>
#include <cstdio>
#include "Log.hpp"
#include "InterAddr.hpp"
using namespace LogModule;


const std::string DefaultDictTxt = "./dictionary.txt"; /* 文档路径 */
const std::string sep = ": "; /* 分割符 */

class Dict
{
public:
    Dict()
        : _pathfile(DefaultDictTxt)
    {

    }

    bool LoadDict()
    {
        /* 打开文件流 + 加载文档的内容到_dict中 */
        std::ifstream in(_pathfile);
        if(!in.is_open())
        {
            /* 没有打开 */
            LOG(LogLevel::ERROR) << "open .txt for dict fail!";
            return false;
        }
        /* 打开了 */
        std::string line;
        while(std::getline(in, line))
        {
            // apple: 苹果
            auto pos = line.find(sep);
            if(pos == std::string::npos)
            {
                LOG(LogLevel::WARING) << "解析: " << line << " 失败";
                continue;
            }
            std::string English = line.substr(0, pos);
            std::string Chinese = line.substr(pos + sep.size());

            if (English.empty() || Chinese.empty())
            {
                LOG(LogLevel::WARING) << "没有有效内容: " << line;
                continue; /* 跳过继续加载下一行 */
            }

            _dict.insert(std::make_pair(English, Chinese));
            LOG(LogLevel::DEBUG) << "加载: " << line;
        }
        in.close(); /* 关闭文件流 */
        return true;
    }

    std::string Translate(const std::string &word, InterAddr &addr)
    {
        auto iter = _dict.find(word);
        if (iter == _dict.end())
        {
            LOG(LogLevel::DEBUG) << "进入到了翻译模块, [" <<  addr.Ip() << " : " <<  addr.Port() << "]# " << word << "->None";
            return "None";
        }
            LOG(LogLevel::DEBUG) << "进入到了翻译模块, [" <<  addr.Ip() << " : " <<  addr.Port() << "]# " << word << "->" << iter->second;
        return iter->second; 
    }

    ~Dict() 
    {}

private:
    const std::string _pathfile;                        /* 存储加载翻译的文档路径 */
    std::unordered_map<std::string, std::string> _dict; /* hash映射单词 */
};